//
//  MKUserInfoViewModer.swift
//  Weibo
//
//  Created by mac on 15/12/15.
//  Copyright © 2015年 MK. All rights reserved.
//

//MARK: -MVVM模式  |Model| <-> |ViewModel| <-> |Controller+View|

//VM:封装网络请求(MKOAuth...控制器中的) 和 业务逻辑(MKBase...控制器中的)
import UIKit
import AFNetworking

class MKUserInfoViewModer: NSObject {
    
    //业务逻辑
    //定义用户信息模型的属性
    var userInfo: MKUserInfo?
    override init() {
        userInfo = MKUserInfo.gotUserInfoData()
        super.init()
    }
    //计算型属性 判断用户是否登录
    var userLogin: Bool {
        return (userInfo?.access_token != nil)
    }
    
    //获取用户名
    var userName: String? {
        return userInfo?.name ?? ""
    }
    
    //获取头像的url
    var iconURL: NSURL? {
        let urlStr = userInfo?.avatar_large ?? ""
        return NSURL(string: urlStr)
    }
    
    //获取token
    var token: String? {
        return userInfo?.access_token
    }
    
    //网络请求
    //获取用户的令牌
    func loadAccess_token(code: String, finished: (isSuccess: Bool) ->()) {
        
        let URLString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        //网络数据请求管理层 获取数据
        MKHTTPRequest.sharedHttpRequest.requestJSONDict(HTTPMethod.POST, URLString: URLString, parameters: parameters) { (isSuccess, isError) -> () in
            
            if isError != nil {
                //请求失败
                
            } else {
                //有数据就字典转模型
                let userInfo = MKUserInfo(dic: isSuccess!)
                //print(userInfo)
                
                //FIXME: - 把获取的finished传递到getUserInfo()
                self.getUserInfo(userInfo, finished: finished)
            }
            
        }
    }
    
    //通过access_token获取用户信息
    func getUserInfo(info: MKUserInfo, finished: (isSuccess: Bool) ->()) {
        
        let URLStr = "https://api.weibo.com/2/users/show.json"
        guard let token = info.access_token, uid = info.uid else {
            return
        }
        let parmeterss = ["access_token" :token, "uid" : uid]
        MKHTTPRequest.sharedHttpRequest.requestJSONDict(HTTPMethod.GET, URLString: URLStr, parameters: parmeterss) { (isSuccess, isError) -> () in
            
            if isError != nil {
                //有错 报错
            } else {
                //有值 进行字典转模型
                let dic = isSuccess!
                let name  = dic["name"] as! String
                let avatar_large = dic["avatar_large"]  as! String
                
                //给上面传递过来的属性赋值
                info.name = name
                info.avatar_large = avatar_large
                
                //进行归档 - 调用MKUserInfo的对象方法 进行归档
                info.saveUserInfoData()
                
                //登录状态的回调
                finished(isSuccess: true)
            }
        }
    }
    
    
}
